package com.andy.springboot.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * md5值工具类
 * @author Andy.ye
 * @date 2018年3月23日 下午3:30:42
 */
public class MD5Util {

	protected static char[] hexDigits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
			'd', 'e', 'f' };

	private MD5Util() {
	}

	public static String getMD5String(String s) {
		try {
			return getMD5String(s.getBytes());
		} catch (NoSuchAlgorithmException var2) {
			return "";
		}
	}

	public static String getMD5String(byte[] bytes) throws NoSuchAlgorithmException {
		MessageDigest messagedigest = MessageDigest.getInstance("MD5");
		messagedigest.update(bytes);
		return bufferToHex(messagedigest.digest());
	}

	private static String bufferToHex(byte[] bytes) {
		return bufferToHex(bytes, 0, bytes.length);
	}

	private static String bufferToHex(byte[] bytes, int m, int n) {
		StringBuffer stringbuffer = new StringBuffer(2 * n);
		int k = m + n;

		for (int l = m; l < k; ++l) {
			appendHexPair(bytes[l], stringbuffer);
		}

		return stringbuffer.toString().toUpperCase();
	}

	private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
		char c0 = hexDigits[(bt & 240) >> 4];
		char c1 = hexDigits[bt & 15];
		stringbuffer.append(c0);
		stringbuffer.append(c1);
	}

	public static void main(String[] args) throws NoSuchAlgorithmException {
		String str = "appkeytestlanguagechinesesingerid1035singername%E5%88%98%E5%BE%B7%E5%8D%8Etimestamp20130506135203year20132345wert";
		System.out.println("MD5:" + getMD5String(str));
	}
}
